module memory; 
use dbg; 
implicit none;
!private;
logical, save :: DBG_VEC_NEW = .TRUE., SAVE_VEC_NEW;
logical, save :: DBG_VEC_IF = .TRUE., SAVE_VEC_IF;
logical, save :: DBG_VEC_ENTRY = .FALSE., SAVE_VEC_ENTRY;
!logical, save :: DBG_VEC_ENTRY = .TRUE.;
integer, parameter :: DUFF_SIZE = 8;
integer, parameter :: DUFF_SIZE_16 = 16;
integer, save :: NEW_VEC_COUNT = 0;

!type VEC_PT  !PT - pointer to type; or type-pointer
! real(R14), pointer :: vp(:); 
!end type
!
!type VEC_ARR_T
!  type(VEC_PT), allocatable :: va(:); !vector-pointer-array
!end type

contains; 

subroutine dbg_vec_all_on();  implicit none;  
  DBG_VEC_NEW = .TRUE.;
  DBG_VEC_IF = .TRUE.;
  DBG_VEC_ENTRY = .TRUE.;
end subroutine

function new_vec(n) result(res);    implicit none;  
  integer, intent(in) :: n;  integer :: status;
  real(R14), dimension(:), pointer :: res;      
  allocate(res(n), STAT=status);
  call dbg_info("-->new_vec()", DBG_VEC_ENTRY);
  res = 0.;     call dbg_vec("res=", res);
  NEW_VEC_COUNT = NEW_VEC_COUNT + 1;
  call dbg_int("NEW_VEC_COUNT=", NEW_VEC_COUNT, DBG_VEC_NEW);
  return;
end function

function new_vec_from(from_p) result(res);   implicit none;  
  integer :: status, mini, maxi;
  real(R14), dimension(:), pointer :: from_p, res;      
  call dbg_info("-->new_vec_from()", DBG_VEC_ENTRY);
  mini = LBOUND(from_p, 1);
  maxi = UBOUND(from_p, 1);
  allocate(res(mini:maxi), STAT=status);
  res = 0.;       call dbg_vec("res=", res);
  NEW_VEC_COUNT = NEW_VEC_COUNT + 1;
  call dbg_int("NEW_VEC_COUNT=", NEW_VEC_COUNT, DBG_VEC_NEW);
  return;
end function

subroutine del_vec(pv);  implicit none;  
  real(R14), dimension(:), pointer :: pv;      
  call dbg_info("-->del_vec()", DBG_VEC_ENTRY);
  call dbg_bool("ASSOCIATED(pv)=", ASSOCIATED(pv), DBG_VEC_IF);
  if (ASSOCIATED(pv)) then
    DEALLOCATE(pv);    !NULLIFY(ptr); !DEALLOCATE() makes it null
    NEW_VEC_COUNT = NEW_VEC_COUNT - 1;
    call dbg_int("NEW_VEC_COUNT=", NEW_VEC_COUNT, DBG_VEC_NEW);
  end if     
  return;
end subroutine

subroutine del_vec2(pv, pv2);  implicit none;  
  real(R14), dimension(:), pointer :: pv, pv2;      
  call del_vec(pv);
  call del_vec(pv2);
  return;
end subroutine

subroutine del_vec3(pv, pv2, pv3);  implicit none;  
  real(R14), dimension(:), pointer :: pv, pv2, pv3;      
  call del_vec(pv);
  call del_vec(pv2);
  call del_vec(pv3);
  return;
end subroutine

end module 